from datetime import datetime
from sqlalchemy.orm import Session
from app.db.db_models import User
from typing import Optional

class DBAuth:
    def __init__(self, session: Session):
        self.session = session
    
    def get_user(self, username: str) -> Optional[User]:
        """根据用户名获取用户"""
        return self.session.query(User).filter(User.username == username).first()

    def save_tokens(self, user_id: int, access_token: str, refresh_token: str, 
                    access_expires: datetime, refresh_expires: datetime):
        """保存访问令牌和刷新令牌到数据库"""
        user = self.session.query(User).filter(User.id == user_id).first()
        if user:
            user.access_token = access_token
            user.refresh_token = refresh_token
            user.access_token_expires_at = access_expires
            user.refresh_token_expires_at = refresh_expires
            self.session.commit()

    def revoke_all_tokens(self, user_id: int):
        """撤销用户的所有令牌"""
        user = self.session.query(User).filter(User.id == user_id).first()
        if user:
            user.access_token = None
            user.refresh_token = None
            self.session.commit()

    def is_token_valid(self, token: str) -> bool:
        """检查 token 是否有效"""
        user_token = self.session.query(User).filter(User.access_token == token, User.is_revoked == False).first()
        if user_token:
            return datetime.now() < user_token.access_token_expires_at
        return False 
    
    def create_user(self, username: str, hashed_password: str):
        """创建用户"""
        new_user = User(username=username, hashed_password=hashed_password)
        self.session.add(new_user)
        self.session.commit()

    def reset_password(self, username: str, password: str):
        """重置密码"""
        user = self.session.query(User).filter(User.username == username).first()
        if user:
            user.hashed_password = password
            self.session.commit()

    def delete_user(self, username: str):
        """删除用户"""
        user = self.session.query(User).filter(User.username == username).first()
        if user:
            self.session.delete(user)
            self.session.commit()

    def get_users(self):
        """获取所有用户"""
        return self.session.query(User).all()
    
    def get_user_by_id(self, user_id: int):
        """根据用户ID获取用户"""
        return self.session.query(User).filter(User.id == user_id).first()
    
    def get_user_by_username(self, username: str):
        """根据用户名获取用户"""
        return self.session.query(User).filter(User.username == username).first()
    
    def get_user_by_email(self, email: str):
        """根据邮箱获取用户"""
        return self.session.query(User).filter(User.email == email).first()

